package com.solcoo.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author yuanfang
 * @verson 创建时间 2012-10-9 下午5:23:55
 */
public class DateUtil {

	public static final long ONE_DAY = 24 * 60 * 60 * 1000;// 周期24小时

	public static final long TEN_SECONDS = 10 * 1000;

	public static final long TEN_MIN = 10 * 60 * 1000;

	public static final long FIVE_MIN = 5 * 60 * 1000;

	public static final String DATE = "yyyy-MM-dd";

	public static final String DATE_TIME = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 获取当天的字符串格式
	 * 
	 * @return
	 */
	public static String getToday() {
		final SimpleDateFormat formatter = new SimpleDateFormat(DATE);
		return formatter.format(new Date());
	}

	public static String getNow() {
		final SimpleDateFormat formatter = new SimpleDateFormat(DATE_TIME);
		return formatter.format(new Date());
	}

	public static String format(Date date, String pattern) {
		if (date == null) {
			return StringUtil.EMPTY;
		}
		if (StringUtil.isBlank(pattern)) {
			return date.toString();
		}
		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		return formatter.format(date);
	}

	public static long getTime(int hour, int min, int sec) {
		final Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MINUTE, min);
		calendar.set(Calendar.MILLISECOND, sec);
		return calendar.getTimeInMillis();
	}

	/**
	 * 取得一个模糊时间段
	 * 
	 * @param time
	 * @param rang
	 * @return
	 */
	public static long randomTime(long time, long rang) {
		Random random = new Random();
		return time + random.nextInt() % rang;
	}

	/**
	 * 取得两个时间差
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static long getBetweenTime(Date time1, Date time2) {
		if (time1 == null || time2 == null) {
			return 0;
		}
		return getBetweenTime(time2.getTime(), time1.getDate());
	}

	/**
	 * 取得两个时间差
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static long getBetweenTime(long time1, long time2) {
		if (time1 == 0 || time2 == 0) {
			return 0;
		}
		return time2 - time1;
	}

	public static Date parse(String strDate, String pattern) {
		return parse(strDate, pattern, new Date());
	}

	public static Date parse(String strDate, String pattern, Date defaultDate) {
		final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(strDate);
		} catch (ParseException e) {
			return defaultDate;
		}
	}

}
